import React from 'react';
import { Layout, message, Icon } from 'antd';
import Cookies from 'js-cookie';
import Menus from './containers/siderMenus';
import MyHeaders from './containers/headers';
import MyCenter from './containers/center';
import { request, http } from '@zny/utils';
import { setLocalStorage } from '@zny/hooks';
import defaultSettings from './defaultSettings';
import styles from './index.less';
import './theme/components.less';
import './theme/form.less';
import './theme/prp.less'; //prp样式覆盖
import { Session } from '@/service/Session';
import { WebVariable } from '@/service/WebVariable';

const { Header, Sider, Content } = Layout;

const compare = (prop: any) => {
  return function (a: any, b: any) {
    return b[prop] - a[prop];
  };
};

const listToTree = (list: any) => {
  if (!Array.isArray(list) || list.length === 0) return list;
  var map: any = {},
    roots = [];
  for (var i = 0; i < list.length; i++) {
    map[list[i].id] = i;
    list[i].children = [];
  }
  for (var i = 0; i < list.length; i++) {
    var node = list[i];
    if (node.parentId == null || node.parentId == 'null') {
      roots.push(node);
    } else {
      list[map[node.parentId]].children.push(node);
    }
  }
  return roots;
};

//定义路由集合，由于从权限接口只能获取到pageId，只能这种折中写法........
let pathnameMap: any = undefined;
let selfThis: any = undefined;
let pathname = '';
export const checkAuthToken = () => {
  const cookie_val = Cookies.get('znyToken');
  const cookie_UserId = Cookies.get('portal_sso');

  if (process.env.NODE_ENV == 'development') {
    //pathname = 'http://10.219.86.03:8001';
    pathname = 'http://localhost:8001';
    //pathname = "http://10.219.86.77:8001"
  } else {
    pathname = location.origin;
  }

  if (cookie_val === undefined || cookie_UserId == undefined) {
    console.log("before WebVariable 1", WebVariable)
    Session.getDefaultSettings().then(() => {
      console.log("after WebVariable 1", WebVariable)
      Session.logout()
      //window.open('http://portal.cs.msdi.cn/r1/SignOnServlet?FromUrl=' + pathname, '_parent');
    })
  } else {
    const deCodeCookie = decodeURIComponent(cookie_val);
    const obj = JSON.parse(deCodeCookie);

    //获取默认设置
    request(`/rjApi/data/getByKey?key=defaultSettings`).then(data => {
      const jsonList = JSON.parse(data.value);
      console.log("before WebVariable", WebVariable)
      Object.assign(WebVariable, jsonList)
      console.log("after WebVariable", WebVariable)

      Object.keys(jsonList).map((key: any) => {
        defaultSettings[key] = jsonList[key];
      });

      console.log(defaultSettings, '获取到的默认信息......');
      setLocalStorage('globalSettings', defaultSettings);
      sessionStorage.setItem('defaultSettings', JSON.stringify(defaultSettings));

      const { _LoginProjectId, _TenantId, sysId }: any = defaultSettings;
      const { accessToken } = obj;

      let headers = {
        _LoginProjectId: _LoginProjectId,
        _TenantId: _TenantId,
        token: accessToken,
        Authorization: accessToken,
      };
      request.extendOptions({
        headers,
      });
      http.extendOptions({
        headers,
      });

      let userId = (
        cookie_UserId.slice(0, 8) +
        '-' +
        cookie_UserId.slice(8, 12) +
        '-' +
        cookie_UserId.slice(12, 16) +
        '-' +
        cookie_UserId.slice(16, 20) +
        '-' +
        cookie_UserId.slice(20, 32)
      ).toUpperCase();
      request(`/api/usm/ProjectUser/GetModelById?id=${userId}`)
        .then(data => {
          if (data) {
            data._LoginProjectId = _LoginProjectId; //兼容原先从userinfo获取项目信息
            data._TenantId = _TenantId; //兼容原先从userinfo获取项目信息
            data.value = { accessToken: accessToken };
            console.log(data, '获取到的用户信息......');
            setLocalStorage('userInfo', data);
            getMenuList(sysId, data.id);
          }
        })
        .catch(error => {
          console.log(error, 'error');
        });
    });
  }
};

const getChildMenuList = (menuList: any) => {
  menuList = menuList.sort(compare('orderIndex'));
  /*
   * 这里记录下跳转路由的方式 （我们暂时应该只有空，和外部地址）
   * menuOpenType，指打开方式。有如下四个值
   *  ''，空，默认
   * NewWindow，新开窗体
   * ExternalUrl，外部地址 (这在http://10.219.13.37:9995/biz-project/Fun上，外部地址和url都要填写。然后取url)
   * PopupWindow，DIV弹窗，前端目前不支持。
   */

  Object.keys(menuList).forEach((key: any) => {
    menuList[key].url =
      menuList[key].url ||
      (!menuList[key].menuOpenType ? pathnameMap[menuList[key].pageId] : '') ||
      '';
    menuList[key].external = menuList[key].menuOpenType == 'ExternalUrl' ? menuList[key].url : '';
    if (menuList[key]['children'].length > 0) {
      getChildMenuList(menuList[key]['children']);
    }
  });
  return menuList;
};

//获取所有菜单
const getMenuList = (sysId: string, userId: string) => {
  request('/api/usm/SysAction/GetActionByUserId', {
    method: 'GET',
    params: {
      sysId: sysId,
      userId: userId,
    },
  }).then(res => {
    if (res) {
      sessionStorage.setItem('menuAllData', JSON.stringify(res)); //保存所有菜单数据
      let list = listToTree(res);
      let allMenuList = getChildMenuList(list);
      if (allMenuList.length < 1) {
        message.info('您没有任何权限!');
        setTimeout(() => {
          Session.logout()
          //window.open('http://portal.cs.msdi.cn/r1/SignOnServlet?FromUrl=' + pathname, '_parent');
        }, 2000);
        return;
      }
      selfThis.setState(() => ({
        allMenuList: allMenuList,
        menuId: allMenuList[0].id,
      }));

      let parentMenuId = sessionStorage.getItem('parentMenuId');
      let pid = sessionStorage.getItem('pid');
      try {
        if (parentMenuId != '' && parentMenuId != null) {
          selfThis.setState({ menuId: parentMenuId });
        } else {
          sessionStorage.setItem('pid', '0');
        }
      } catch (error) {
        console.log(error, 'error');
      }
    } else {
      message.info('您没有任何权限!');
      setTimeout(() => {
        Session.logout()
        //window.open('http://portal.cs.msdi.cn/r1/SignOnServlet?FromUrl=' + pathname, '_parent');
      }, 2000);
    }
  });
};

class BasicLayout extends React.Component<{}, { allMenuList: any; visible: any; menuId: string }> {
  constructor(props: any) {
    super(props);
    this.state = {
      allMenuList: [],
      visible: false,
      menuId: '',
    };
  }

  menuClick = (index: any, menuId: string) => {
    this.setState({ menuId: menuId });
    sessionStorage.setItem('parentMenuId', menuId);
    sessionStorage.setItem('pid', index);
  };

  componentWillMount() {
    selfThis = this;
    console.log('进入页面......');
    request('/rjApi/page')
      .then(res => {
        pathnameMap = res.reduce((dict: any, item: any) => {
          dict[item.id] = item.pathname;
          return dict;
        }, {});
      })
      .catch(err => {
        console.log(err, 'err');
      });
  }

  componentDidMount() {
    console.log('加载页面......');
    checkAuthToken();
  }

  render() {
    const { allMenuList, visible, menuId } = this.state;
    const { children } = this.props;
    var parthname = children.props.location.pathname;
    return allMenuList.length > 0 ? (
      <div className={styles.container}>
        <Layout className={styles.layouts}>
          <Header className={styles.headers}>
            <MyHeaders
              props={allMenuList}
              setToggle={(e: any) => {
                this.setState({ collapsed: e });
              }}
              setDrawer={(i: any) => {
                this.setState({ visible: i });
              }}
              setIsTrue={(isTrue: boolean) => {
                this.setState({ width: isTrue ? 0 : 280 });
              }}
            />
          </Header>
          <Layout>
            <div className={styles.newLayouts}>
              <div className={styles.menuControl}>
                <div className={styles.firstMenu}>
                  {allMenuList.map((item: any, index: number) => {
                    return (
                      !item.isHide && (
                        <div
                          className={`${styles.item} ${menuId == item.id ? styles.active : ''}`}
                          onMouseOver={() => {
                            this.menuClick(index, item.id);
                          }}
                        >
                          <div>
                            <Icon type="audit" style={{ fontSize: '20px' }}></Icon>
                          </div>
                          <div>
                            <span className={styles.title}>{item.name.substring(0, 4)}</span>
                          </div>
                        </div>
                      )
                    );
                  })}
                </div>
                <div className={styles.subMenu}>
                  <Menus menuList={allMenuList} props={this.props} />
                </div>
              </div>
              <div style={{ flex: '1', position: 'relative', width: 0 }}>
                {parthname.indexOf('biz-resource') != -1 ||
                  parthname.indexOf('biz-personal') != -1 ||
                  parthname.indexOf('/biz-Integrate/views/RelatedList/department') != -1 ||
                  parthname.indexOf('/biz-Integrate/views/RelatedList/peopleList') != -1 ? (
                    <Content className={styles.contentsNew}>
                      {/* 个人中心 */}
                      <MyCenter
                        visible={visible}
                        SetVisible={() => {
                          this.setState({ visible: false });
                        }}
                      ></MyCenter>
                      {/* 模块主体 */}
                      <div className={styles.main}>{this.props.children}</div>
                    </Content>
                  ) : (
                    <Content className={styles.contents}>
                      {/* 个人中心 */}
                      <MyCenter
                        visible={visible}
                        SetVisible={() => {
                          this.setState({ visible: false });
                        }}
                      ></MyCenter>
                      {/* 模块主体 */}
                      <div className={styles.main}>{this.props.children}</div>
                    </Content>
                  )}
              </div>
            </div>
          </Layout>
        </Layout>
      </div>
    ) : (
        ''
      );
  }
}

export default BasicLayout;
